unit user;

interface

uses
  Classes;

type
  TUserAction = (acAdd, acEdit, acDelete);

  TUser = class(TCollectionItem)
  private
    FEnabled: Boolean;
    FUserName: string;
    FPassword: string;
  public
    property UserName: string read FUserName write FUserName;
    property Password: string read FPassword write FPassword;
    property Enabled: Boolean read FEnabled write FEnabled;
  end;

  TUsers = class(TCollection)
  private
    function GetItem(AIndex: Integer): TUser;
    function GetFileName: string;
  public
    constructor Create;
    procedure LoadFromFile;
    procedure SaveToFile;
    class function UserEnabled(AUser, APass: string): Boolean;
    property Items[AIndex: Integer]: TUser read GetItem; default;
  end;

implementation

uses
  SysUtils;

{ TUsers }

constructor TUsers.Create;
begin
  inherited Create(TUser);
end;

function TUsers.GetFileName: string;
begin
  Result := ExtractFilePath(ParamStr(0)) + '\users.dat';
end;

function TUsers.GetItem(AIndex: Integer): TUser;
begin
  Result := TUser(inherited GetItem(AIndex));
end;

procedure TUsers.LoadFromFile;
var
  lFile: TStringList;
  I: Integer;
  lUser: string;
  lPass: string;
  lEnabled: Char;
begin
  if FileExists(GetFileName) then
  begin
    lFile := TStringList.Create;
    try
      lFile.LoadFromFile(GetFileName);
      for I := 0 to lFile.Count - 1 do
      begin
        lUser := Copy(lFile[I], 0, Pos(';', lFile[I]) - 1);
        lFile[I] := Copy(lFile[I], Pos(';', lFile[I]) + 1, Length(lFile[I]));
        lPass := Copy(lFile[I], 0, Pos(';', lFile[I]) - 1);
        lFile[I] := Copy(lFile[I], Pos(';', lFile[I]) + 1, Length(lFile[I]));
        lEnabled := lFile[I][1];
        with TUser(Add) do
        begin
          UserName := lUser;
          Password := lPass;
          Enabled := (lEnabled = 'T');
        end;
      end;
    finally
      lFile.Free;
    end;
  end;
end;

procedure TUsers.SaveToFile;
var
  lFile: TStringList;
  I: Integer;
  lEnabled: Char;
begin
  lFile := TStringList.Create;
  try
    for I := 0 to Count - 1 do
    begin
      with Items[I] do
      begin
        if Enabled then
          lEnabled := 'T'
        else
          lEnabled := 'F';
        lFile.Add(UserName + ';' + Password + ';' + lEnabled);
      end;
    end;
    lFile.SaveToFile(GetFileName);
  finally
    lFile.Free;
  end;
end;

class function TUsers.UserEnabled(AUser, APass: string): Boolean;
var
  lUsers: TUsers;
  I: Integer;
begin
  Result := False;
  lUsers := TUsers.Create;
  try
    lUsers.LoadFromFile;
    for I := 0 to lUsers.Count - 1 do
    begin
      Result := (lUsers[I].UserName = AUser);
      Result := (Result) and (lUsers[I].Password = APass);
      Result := (Result) and (lUsers[I].Enabled);
      if Result then
        Break;
    end;
  finally
    lUsers.Free;
  end;
end;

end.
